<?php
////require(dirname(__FILE__).'/proxy_controller_mock.php');
if(!defined("IS_LOAD_TASK_CONTROLLER")){
    require_once (dirname(__FILE__) . "/inc/session_auth.php");
    // we don't have to update $_SESSION
    ob_start(); // we buffer everything, because we need to update $_SESSION anytime
    session_write_close();
}else{
	// If Session not started
	// Fix session_start() [function.session-start]: Cannot send session cache limiter - headers already sent
	if(session_id() == ''){
    session_start();
	}
    $_SESSION['uid'] = 1;
}
if(!isset($g_GetPost)){
    $g_GetPost = array_merge($_GET,$_POST);
}else{
    $g_GetPost = array_merge($g_GetPost,$_GET,$_POST);
}
// config
require_once (dirname(__FILE__) . "/inc/config.php");
// error code
require_once (dirname(__FILE__) . "/inc/proxy_errorcode.php");
require_once (dirname(__FILE__) . "/inc/response.php");
// serverlist
require_once (dirname(__FILE__) . "/inc/class/server/ServerDao.php"); // automatically include serverdb class
require_once (dirname(__FILE__) . "/inc/class/init.php");

function update_timestamp($timestamp){
    global $g_GetPost;
    // update timestamp
    if(isset($g_GetPost["serverid"]) && is_numeric($g_GetPost["serverid"]) && isset($_SESSION['uid']) && is_numeric($_SESSION['uid'])){
        $userid = $_SESSION['uid'];
        $serverdb = new WFServerDao($GLOBALS['wfconf_dbconfig'], $userid);
        if(! $serverdb->isFailed()){
            $serverdb->update_lastcheck($g_GetPost["serverid"], $timestamp);
        }
    }
}
function proxy_error($errcode, $errmsg){
    // JSON
    make_error_response($errcode, $errmsg);
    // connect to server failed, so reset timestamp
    update_timestamp(0);
    exit();
}

mydebug_log("[PROXY-REQUEST] starting");
/* check module */
$server_module = $g_GetPost['module'];
mydebug_log("[PROXY-REQUEST] module: " . $server_module);
$isDirectoryTraversal = WF::getSecurityFactory()->getSanitize()->isDirectoryTraversal($server_module);
if(true === $isDirectoryTraversal){
    mydebug_log("Bad guy come in!!");
    proxy_error(WF_PROXY_ERR_INIT_INVALID_MODULE, WF_PROXY_ERR_INIT_INVALID_MODULE_MSG);
}
$intUserGeneratedInfoOfWidget = (array_key_exists('userGenerated', $g_GetPost)) ? $g_GetPost['userGenerated'] : 0;
if($intUserGeneratedInfoOfWidget == 1){
    $strProxyDir = USER_GENERATED_PROXY_DIR;
}else{
    $strProxyDir = PROXY_DIR;
}
$myproxy_file = $strProxyDir . "/" . $server_module . "/Proxy.php";
// does file exist?
if(file_exists($myproxy_file)){
    include ($myproxy_file);
}else{
    proxy_error(WF_PROXY_ERR_INIT_INVALID_MODULE, WF_PROXY_ERR_INIT_INVALID_MODULE_MSG);
}

// does class exist?
if(! class_exists("WFProxy")){
    proxy_error(WF_PROXY_ERR_INIT_MODULE_ERROR, WF_PROXY_ERR_INIT_MODULE_ERROR_MSG);
}
if( $g_GetPost["ApplyProxy"]==1)
{
	if($g_GetPost["ProxyType"]==1)
	{
		$g_GetPost["ProxyType"]="sock5";
  }
  else
  {
  	$g_GetPost["ProxyType"]="http";
  }
}
// create the object
$request = new WFProxy($g_GetPost, $wfconf_dbconfig);

if($request->isFailed()){
    mydebug_log("[PROXY-REQUEST] creating WFProxy object failed: " . $request->getErrMessage());
    proxy_error($request->getErrCode(), WF_PROXY_ERR_INIT_OTHERS_MSG . ": " . $request->getErrMessage());
}
// is it act=check ?
if(isset($g_GetPost["act"]) && $g_GetPost["act"] == "check"){
    // check status
    mydebug_log("[PROXY-REQUEST] proxy checking remote server. serverid: " . $g_GetPost["serverid"]);
    $alive = $request->proxy_check();
    if($alive == false){
        mydebug_log("[PROXY-REQUEST] proxy checking failed: " . $request->getErrMessage());
        proxy_error($request->getErrCode(), WF_PROXY_CHK_DOWN_MSG . ": " . $request->getErrMessage());
    }
    update_timestamp(time());
    make_successful_response(WF_PROXY_CHK_ALIVE_MSG, null);
    //ob_end_flush();
    exit(); // stop here
}elseif(isset($g_GetPost["act"]) && $g_GetPost["act"] == "register"){ // is it act=check_result ?
    // check status
    mydebug_log("[PROXY-REQUEST] register to remote server task result.");
    $result = $request->proxy_register();
    if($request->isFailed()){
        mydebug_log("[PROXY-REQUEST] proxy task_getresult failed: " . $request->getErrMessage());
        proxy_error($request->getErrCode(), WF_PROXY_ERR_EXEC_OTHERS_MSG . ": " . $request->getErrMessage());
    }
    echo $result;
    exit(); // stop here
}
elseif(isset($g_GetPost["act"]) && $g_GetPost["act"] == "task_result"){ // is it act=check_result ?
    // check status
    mydebug_log("[PROXY-REQUEST] proxy checking remote server task result. product_id: " . $g_GetPost["product_id"]);
    $result = $request->task_result();
    if($request->isFailed()){
        mydebug_log("[PROXY-REQUEST] proxy task_getresult failed: " . $request->getErrMessage());
        proxy_error($request->getErrCode(), WF_PROXY_ERR_EXEC_OTHERS_MSG . ": " . $request->getErrMessage());
    }
    echo $result;
    exit(); // stop here
}
// proxy excutes tasks
mydebug_log("[PROXY-REQUEST] proxy exec.");
$request->proxy_exec();
if($request->isFailed()){
    mydebug_log("[PROXY-REQUEST] proxy exec failed: " . $request->getErrMessage());
    proxy_error($request->getErrCode(), WF_PROXY_ERR_EXEC_OTHERS_MSG . ": " . $request->getErrMessage());
}
// yes, server is alive
update_timestamp(time());
// proxy output
mydebug_log("[PROXY-REQUEST] proxy output.");
$request->proxy_output();
if($request->isFailed()){
    mydebug_log("[PROXY-REQUEST] proxy output failed: " . $request->getErrMessage());
    proxy_error($request->getErrCode(), WF_PROXY_ERR_RESULT_OTHERS_MSG . ": " . $request->getErrMessage());
}
//ob_end_flush();
?>
